package com.example.plus.file.translator.action;

import com.example.plus.file.translator.domain.FileTranslator;
import com.example.plus.file.translator.util.TranslatorUtil;
import org.junit.Test;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 翻译的接口层
 *
 * @author zhouxl
 * @DATE 2020/12/4
 * @descriptoin
 */
public class FileTranslatorAction {

    @Test
    public void getDirFileZhTest() throws IOException {
        String inDirPath = "D:\\档案4\\archive-gamsBackend\\src\\main\\webapp\\archives\\common\\scan\\javascripts";
        String ignoreFileName = "page";
        String outPath = "D:\\新建文件夹\\test文件\\包下所有的中文数据.txt";
        List<FileTranslator> list = new ArrayList<>();
        getDirFileZh(inDirPath, ignoreFileName, list);
        Set<String> keyList = rmRepeatKey(list);
        BufferedWriter writer = createBufferedWriter(outPath);
        writer.newLine();
        for (String key : keyList) {
            writer.write("=" + key);
            writer.newLine();
        }
        writer.newLine();
        writer.flush();
        writer.close();
    }

    public Set<String> rmRepeatKey(List<FileTranslator> list) {
        Set<String> keyList = new HashSet<>();
        for (FileTranslator ft : list) {
            Map<String, String> chinese = ft.getChinese();
            Set<Map.Entry<String, String>> es = chinese.entrySet();
            for (Map.Entry<String, String> e : es) {
                String key = e.getKey();
                keyList.add(key);
            }
        }
        return keyList;
    }

    /**
     * 提取文件夹下所有的中文数据
     */
    public void getDirFileZh(String inDirPath, String ignoreFileName, List<FileTranslator> mapList) throws IOException {
        File file = new File(inDirPath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                getDirFileZh(f.getAbsolutePath(), ignoreFileName, mapList);
            }
        } else {
            String fileContent = getFileContentString(inDirPath);
            String fileType = getFileType(inDirPath);
            String str = "";
            if ("java".equals(fileType)) {   // java文件
                str = javaFile(fileContent);
            } else if ("jsp".equals(fileType)) {  // jsp文件
                str = jspFile(fileContent);
            }
            // 中文
            Map<String, String> chinese = new HashMap<>();
            FileTranslator translator = new FileTranslator();
            String regex = "([\\u4e00-\\u9fa5]+)";
            Matcher matcher = Pattern.compile(regex).matcher(str);
            String path = ignoreFilePrefixPath(inDirPath, ignoreFileName);
            while (matcher.find()) {
                String group = matcher.group();
                if (!chinese.containsKey(group)) {
                    chinese.put(group, path);
                }
            }
            translator.setChinese(chinese);
            mapList.add(translator);
        }
    }

    @Test
    public void translateZhToEn() throws Exception {
        String inPath = "D:\\档案3\\archive-core\\overlays\\com.yinhai.ta3-modules-authority-ta3-websource-4.0.1-20170719.070609-2\\WEB-INF\\page\\org\\position\\similarauthority\\grantSimilarAuthority.jsp";
        String outPath = "D:\\新建文件夹\\test文件\\";
        String ignoreFileName = "page";
        FileTranslator fileTranslator = createFileTranslator(inPath, outPath, ignoreFileName);
        BufferedWriter writer = createBufferedWriter(fileTranslator.getOutPath());

        Map<String, String> chinese = fileTranslator.getChinese();
        Map<String, String> english = fileTranslator.getEnglish();
        Set<Map.Entry<String, String>> es = chinese.entrySet();

        /*
        开头
         */
        writer.newLine();
        writer.write("#region " + fileTranslator.getIgnoreFileName() + "    中文=英文");
        writer.newLine();
        writer.newLine();
        for (Map.Entry<String, String> e : es) {
            String key = e.getKey();
            String en = english.get(key);
            writer.write(key + "=" + en);
            writer.newLine();
        }
        writer.newLine();
        writer.write("#endregion " + fileTranslator.getIgnoreFileName() + "    中文=英文");
        writer.newLine();
        writer.newLine();
        writer.flush();
        writer.close();
    }

    /**
     * 测试代码 - 测试翻译一个文件夹下所有需要的翻译的中文
     *
     * @throws Exception
     */
    @Test
    public void translateDirTest() throws Exception {
        String dirPath = "D:\\档案4\\archive-gamsBackend\\src\\main\\webapp\\archives\\common\\scan\\javascripts";
        String outPath = "D:\\新建文件夹\\test文件\\test3.txt";
        String ignoreFileName = "webapp";
        translateDir(dirPath, outPath, ignoreFileName);
    }

    /**
     * 测试代码 - 测试翻译一个文件下所有需要的翻译的中文
     *
     * @throws Exception
     */
    @Test
    public void translateFileTest() throws Exception {
        String dirPath = "D:\\档案4\\archive-gamsBackend\\src\\main\\webapp\\archives\\common\\scan\\javascripts";
        String outPath = "D:\\新建文件夹\\test文件\\test3.txt";
        String ignoreFileName = "webapp";
        translateDir(dirPath, outPath, ignoreFileName);
    }

    /**
     * 翻译目录下所有的文件信息
     */
    public void translateDir(String dirPath, String outPath, String ignoreFileName) throws Exception {
        File file = new File(dirPath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                translateFile(f.getAbsolutePath(), outPath, ignoreFileName);
            }
        } else {
            translateFile(file.getAbsolutePath(), outPath, ignoreFileName);
        }
    }

    /**
     * 翻译文件
     *
     * @param inPath
     * @param outPath
     * @param ignoreFileName
     * @throws Exception
     */
    public void translateFile(String inPath, String outPath, String ignoreFileName) throws Exception {
        FileTranslator fileTranslator = createFileTranslator(inPath, outPath, ignoreFileName);
        BufferedWriter writer = createBufferedWriter(fileTranslator.getOutPath());
        writeFile(writer, fileTranslator);
    }

    /**
     * 将翻译好的内容写入文件中
     *
     * @param writer
     * @param fileTranslator
     * @throws IOException
     */
    public void writeFile(BufferedWriter writer, FileTranslator fileTranslator) throws IOException {
        if (fileTranslator == null) {
            return;
        }
        Map<String, String> chinese = fileTranslator.getChinese();
        Map<String, String> english = fileTranslator.getEnglish();

        /*
        开头的数据 - 中文
         */
        writeFileStart(writer, fileTranslator.getIgnoreFileName(), "zh");
        Set<Map.Entry<String, String>> es = chinese.entrySet();
        for (Map.Entry<String, String> e : es) {
            String key = e.getKey();
            String value = e.getValue();
            String convertStr = convertString(english.get(key));
            writer.write(fileTranslator.getIgnoreFileName() + "_" + convertStr + "=" + key);
            writer.newLine();
        }
        /*
        结尾的数据 - 中文
         */
        writeFileEnd(writer, fileTranslator.getIgnoreFileName(), "zh");


        /*
        开头的数据 - 英文
         */
        writeFileStart(writer, fileTranslator.getIgnoreFileName(), "en");
        es = english.entrySet();
        for (Map.Entry<String, String> e : es) {
            String key = e.getKey();
            String value = e.getValue();
            String convertStr = convertString(english.get(key));
            writer.write(fileTranslator.getIgnoreFileName() + "_" + convertStr + "=" + value);
            writer.newLine();
        }
        /*
        结尾的数据 - 英文
         */
        writeFileEnd(writer, fileTranslator.getIgnoreFileName(), "en");
        writer.flush();
        writer.close();
    }

    /**
     * 文件结尾 - 写入
     */
    public void writeFileEnd(BufferedWriter writer, String ignoreName, String language) throws IOException {
        if ("zh".equals(language)) {
            writer.write("#endregion " + ignoreName + " --中文");
        } else if ("en".equals(language)) {
            writer.write("#endregion " + ignoreName + " --英文");
        }
        writer.newLine();
        writer.newLine();
        writer.newLine();
    }

    /**
     * 文件开头 - 写入
     */
    public void writeFileStart(BufferedWriter writer, String ignoreName, String language) throws IOException {
        if ("zh".equals(language)) {
            writer.write("#region " + ignoreName + " --中文");
        } else if ("en".equals(language)) {
            writer.write("#region " + ignoreName + " --英文");
        }
        writer.newLine();
    }

    /**
     * 构建字节流输出对象
     *
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public BufferedWriter createBufferedWriter(String path) throws FileNotFoundException {
        return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true)));
    }

    /**
     * 创建FileTranslator对象信息
     *
     * @param inPath
     * @param outPath
     * @param ignoreFileName
     */
    public FileTranslator createFileTranslator(String inPath, String outPath, String ignoreFileName) throws Exception {
        FileTranslator translator = new FileTranslator();
        String fileContent = getFileContentString(inPath);
        String fileType = getFileType(inPath);
        String str = "";
        if ("java".equals(fileType)) {   // java文件
            str = javaFile(fileContent);
        } else if ("jsp".equals(fileType)) {  // jsp文件
            str = jspFile(fileContent);
        } else if ("js".equals(fileType)) {
            str = jsFile(fileContent);
        } else {

        }
        // 中文
        Map<String, String> chinese = new HashMap<>();
        // 英文
        Map<String, String> english = new HashMap<>();
        String regex = "([\\u4e00-\\u9fa5]+)";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        String path = ignoreFilePrefixPath(inPath, ignoreFileName);
        while (matcher.find()) {
            String group = matcher.group();
            if (!chinese.containsKey(group)) {
                chinese.put(group, path);
            }
        }
        Set<Map.Entry<String, String>> entries = chinese.entrySet();
        for (Map.Entry<String, String> e : entries) { // 英文
            String zh = e.getKey();
            String en = TranslatorUtil.translate("zh-CN", "en", zh);
            english.put(zh, en);
        }
        // 构建对象
        translator.setFileContent(fileContent);
        translator.setChinese(chinese);
        translator.setEnglish(english);
        translator.setFileType(fileType);
        translator.setIgnoreFileName(path);
        translator.setInPath(inPath);
        translator.setOutPath(outPath);
        return translator;
    }

    /**
     * 转换字符串格式
     * 例子：
     * Hello world is good -> helloWorldIsGood
     *
     * @param line
     * @return
     */
    public String convertString(String line) {
        String newLine = "";
        StringBuffer sb = new StringBuffer();
        String[] words = line.split(" ");
        for (String str : words) {
            sb.append(str.substring(0, 1).toUpperCase() + str.substring(1, str.length()));
        }
        newLine = sb.toString();
        return newLine.substring(0, 1).toLowerCase() + newLine.substring(1);
    }


    /**
     * jsp文件处理
     *
     * @param fileContent
     * @return
     */
    public String jspFile(String fileContent) {
        // jsp文件处理
        String str = fileContent.replaceAll("<%--([\\w\\W]{1,})--%>", "");
        str = str.replaceAll("/([*]{1,})([\\w\\W]{0,}?)\\*\\/", "");
        str = str.replaceAll("//([\\w\\W]{1,10}?)[\\u4e00-\\u9fa5]+", "");
        return str;
    }

    /**
     * java文件处理方式
     *
     * @param fileContent
     * @return
     */
    public String javaFile(String fileContent) {
        // java文件处理
        String str = fileContent.replaceAll("/([*]{1,})([\\w\\W]{0,}?)\\*\\/", "");
        str = str.replaceAll("//([\\w\\W]{1,10}?)[\\u4e00-\\u9fa5]+", "");
        return str;
    }

    /**
     * js文件处理方式
     *
     * @param fileContent
     * @return
     */
    public String jsFile(String fileContent) {
        // js文件处理
        String str = fileContent.replaceAll("/([*]{1,})([\\w\\W]{0,}?)\\*\\/", "");
        str = str.replaceAll("//([\\w\\W]{1,10}?)[\\u4e00-\\u9fa5]+", "");
        return str;
    }

    /**
     * 忽略文件前缀
     *
     * @param filePath
     * @param ignoreFile
     * @return
     */
    public String ignoreFilePrefixPath(String filePath, String ignoreFile) {
        String path = filePath.replaceAll("\\\\", "_");
        path = path.replaceAll("\\.", "_");
        int i = path.indexOf(ignoreFile);
        if (i == -1) {  // 说明没有找到
            return path;
        } else {
            i = i + ignoreFile.length();
            path = path.substring(i + 1);
        }
        return path;
    }

    /**
     * 获取文件类型
     *
     * @param inPath
     * @return
     */
    public String getFileType(String inPath) {
        int i = inPath.lastIndexOf(".");
        if (i == -1) {
            return "";
        }
        return inPath.substring(i + 1).toLowerCase();
    }


    /**
     * 通过文件路径获取文件字符串信息
     *
     * @param path
     * @return
     * @throws IOException
     */
    public String getFileContentString(String path) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = createBufferedReader(path);
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }

    /**
     * 获取字符输入流对象
     *
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public BufferedReader createBufferedReader(String path) throws FileNotFoundException {
        return new BufferedReader(new FileReader(new File(path)));
    }

}
